package com.woyao;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.woyao.core.PayResult;
import com.woyao.core.model.Balance;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.GetBalanceResponse;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.DateUtil;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.Map;

import retrofit2.Call;

public class MoneyActivity extends AppCompatActivity {
    private LinearLayout alllist = null;
    private TextView balanceAmountTxt = null;
    private TextView payAmountTxt = null;
    private Button payButton = null;
    ProgressDialog progressDialog;
    private GetBalanceResponse balance;
    private static final int SDK_PAY_FLAG = 1;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            PayResult result = new PayResult((Map<String, String>) msg.obj);

            String resultStatus = result.getResultStatus();
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                Toast.makeText(MoneyActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                payAmountTxt.setText("");
                loadData();
            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                Toast.makeText(MoneyActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
            }


        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_money);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout


        alllist = (LinearLayout)findViewById(R.id.balance_list);
        balanceAmountTxt = (TextView) findViewById(R.id.balance_amount);
        payAmountTxt = (EditText) findViewById(R.id.pay_amount);
        payButton = (Button) findViewById(R.id.alipay);

        payButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                appPay();
            }
        });

        Intent intent = getIntent();

        Double money = intent.getDoubleExtra("money", 0.0);
        if ( money >0 ) {
            payAmountTxt.setText(money + "");
        }else{
            payAmountTxt.setText("");
        }

        loadData();


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        finish();
        return true;
    }

    private void appPay(){

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在启动支付······");
        progressDialog.show();

        final String payamount = payAmountTxt.getText().toString();
        AsyncTask<Void,Void,BaseResponse> task =new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<BaseResponse> responseCall = svc.getOrder(WoyaoooApplication.userId,payamount );
                try {
                    BaseResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final BaseResponse response) {
                progressDialog.dismiss();
                if (response.isSuccess()){
                    pay(response.getMessage());
                }
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void)null);
    }

    private void pay(final String orderInfo ){

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(MoneyActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo,true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();

    }

    private AsyncTask<Void,Void,GetBalanceResponse> task = null;
    private void loadData(){
        if(task != null)return;

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在获取数据······");
        progressDialog.show();

        task =new AsyncTask<Void, Void, GetBalanceResponse>() {
            @Override
            protected GetBalanceResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetBalanceResponse> responseCall = svc.getBalance(WoyaoooApplication.userId);
                try {
                    GetBalanceResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetBalanceResponse response) {
                progressDialog.dismiss();
                render(response);
                task = null;
            }
            @Override
            protected void onCancelled() {
                progressDialog.dismiss();
            }
        };
        task.execute((Void)null);
    }
    private void render(GetBalanceResponse response){
        if (response.isSuccess() == false ){
            return;
        }

        balance = response ;

        LinearLayout item = (LinearLayout) LayoutInflater.from(MoneyActivity.this).inflate(R.layout.balance_item, null);

        TextView theid = (TextView)item.findViewById(R.id.balance_id);
        TextView thetype = (TextView)item.findViewById(R.id.balance_type);
        TextView theamount = (TextView)item.findViewById(R.id.balance_amount);
        TextView thestatus = (TextView)item.findViewById(R.id.balance_status);
        TextView create_time = (TextView)item.findViewById(R.id.balance_created);

        theid.setTextColor( ContextCompat.getColor(this, R.color.colorWhite) );
        theid.setBackgroundColor(  ContextCompat.getColor(this, R.color.colorTextSecondary) );

        thetype.setTextColor( ContextCompat.getColor(this, R.color.colorWhite) );
        thetype.setBackgroundColor(  ContextCompat.getColor(this, R.color.colorTextSecondary) );

        theamount.setTextColor( ContextCompat.getColor(this, R.color.colorWhite) );
        theamount.setBackgroundColor(  ContextCompat.getColor(this, R.color.colorTextSecondary) );

        thestatus.setTextColor( ContextCompat.getColor(this, R.color.colorWhite) );
        thestatus.setBackgroundColor(  ContextCompat.getColor(this, R.color.colorTextSecondary) );

        create_time.setTextColor( ContextCompat.getColor(this, R.color.colorWhite) );
        create_time.setBackgroundColor(  ContextCompat.getColor(this, R.color.colorTextSecondary) );

        alllist.addView(item);

        balanceAmountTxt.setText( "账户余额: "+ response.getMessage()+" 元");
            for(Balance bal : response.getContent()){
                item = (LinearLayout) LayoutInflater.from(MoneyActivity.this).inflate(R.layout.balance_item, null);

                 theid = (TextView)item.findViewById(R.id.balance_id);
                 thetype = (TextView)item.findViewById(R.id.balance_type);
                 theamount = (TextView)item.findViewById(R.id.balance_amount);
                 thestatus = (TextView)item.findViewById(R.id.balance_status);
                 create_time = (TextView)item.findViewById(R.id.balance_created);

                theid.setText( bal.getId() +""  );
                thetype.setText(bal.getType());
                theamount.setText(bal.getAmount()+"");
                thestatus.setText(bal.getStatus());
                create_time.setText( DateUtil.format(bal.getCreated()));

                alllist.addView(item);
            }


    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent();
            setResult(0, intent);
            finish();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
